const { ObjectId } = require("mongodb");

async function listArticleByCategory(ctx, params) {
  const categoryId = params.categoryId;
  const pageNo = parseInt(params.pageNo) || 1;
  const pageSize = parseInt(params.pageSize) || 10;

  const filter = {};

  if (categoryId) {
    filter.category = {
      $eq: new ObjectId(categoryId),
    };
  }

  const articleColl = ctx.mongoClient.db().collection("articles");
  const total = await articleColl.countDocuments(filter);
  const items = await articleColl
    .aggregate([
      {
        $match: filter,
      },
      {
        $sort: {
          createdAt: -1,
        },
      },
      {
        $skip: (pageNo - 1) * pageSize, // 跳过多少条
      },
      {
        $limit: pageSize, // 取多少条
      },
      {
        $lookup: {
          from: "users", // 关联的集合
          localField: "ownerId", // 当前集合的字段
          foreignField: "_id", // 关联集合的字段
          as: "owner", // 关联集合的数据存储在哪个字段
        },
      },
      {
        $unwind: "$owner",
      },
      {
        $lookup: {
          from: "categories", // 关联的集合
          localField: "category", // 当前集合的字段
          foreignField: "_id", // 关联集合的字段
          as: "categories", // 关联集合的数据存储在哪个字段
        },
      },
      {
        $unwind: "$categories",
      },
      {
        $project: {
          ownerId: 0,
          category: 0,
          owner: {
            _id: 0,
            createdAt: 0,
            updatedAt: 0,
            username: 0,
            password: 0,
          },
        },
      },
    ])
    .toArray();

  return {
    total,
    items,
  };
}

async function getArticleDetail(ctx, id) {
  const articleColl = ctx.mongoClient.db().collection("articles");
  const items = await articleColl
    .aggregate([
      {
        $match: {
          _id: new ObjectId(id),
        },
      },
      {
        $lookup: {
          from: "users", // 关联的集合
          localField: "ownerId", // 当前集合的字段
          foreignField: "_id", // 关联集合的字段
          as: "owner", // 关联集合的数据存储在哪个字段
        },
      },
      {
        $unwind: "$owner",
      },
      {
        $lookup: {
          from: "categories", // 关联的集合
          localField: "category", // 当前集合的字段
          foreignField: "_id", // 关联集合的字段
          as: "categories", // 关联集合的数据存储在哪个字段
        },
      },
      {
        $unwind: "$categories",
      },
    ])
    .toArray();

  return items[0];
}

module.exports = {
  listArticleByCategory,
  getArticleDetail,
};
